/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package JFreeChartExtensions.Fitters;

import JFreeChartExtensions.Series.XYExtendedIntervalSeries;
import JFreeChartExtensions.Series.XYRegressionSeries;

/**
 *
 * @author Nobody
 */
public class LinearReggression implements IReggression {

    private double xMin = Double.MAX_VALUE;
    private double xMax = 0;
    private String lastFunctionFormula;

    private void findMaxAndMin(XYExtendedIntervalSeries data) {
        for (int j = 0; j < data.getItemCount(); j++) {
            double x = data.getX(j).doubleValue();
            if (x < xMin) {
                xMin = x;
            }
            if (x > xMax) {
                xMax = x;
            }
        }

    }

    @Override
    public XYRegressionSeries regress(XYExtendedIntervalSeries data) {
        findMaxAndMin(data);

        int n = data.getItemCount();
        double sx = 0, sy = 0, sxx = 0, sxy = 0, syy = 0;
        for (int j = 0; j < n; j++) {
            double x = data.getX(j).doubleValue();
            double y = data.getYValue(j);
            sx += x;
            sy += y;
            sxx += x * x;
            sxy += x * y;
            syy += y * y;
        }
        double b = (n * sxy - sx * sy) / (n * sxx - sx * sx);
        double a = sy / n - b * sx / n;
        if (b > 0) {
            lastFunctionFormula = String.format("y(x) = %f * x + %f", a, b);
        } else {
            lastFunctionFormula = String.format("y(x) = %f * x  %f", a, b);
        }
        XYRegressionSeries regr = new XYRegressionSeries(lastFunctionFormula);
        regr.add(xMin, a + b * xMin);
        regr.add(xMax, a + b * xMax);
        return regr;
    }

    @Override
    public String toString() {
        return "LinearReggression";
    }
}
